package com.jemframework;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;

public class JagUtils {

  private static final Object[][] EMPTY_ARRAY = new Object[0][0];

  private static final String RESOURCE_BUNDLE_NAME = "messages";

  public static EntityManager em() throws NamingException {
    InitialContext context = new InitialContext();
    EntityManager em = (EntityManager) context.lookup("java:/EntityManager");
    return em;
  }

  public static boolean areEqual(Object a, Object b) {

    if (a != null && b != null) {
      // a != null
      // b != null
      return a.equals(b);
    }

    if (a != null) {
      // a != null
      // b - ?
      return b != null;

    } else {
      // a == null
      // b -?
      return b == null;
    }
  }

  @SuppressWarnings("unchecked")
  public static List asList(Collection collection) {

    if (collection == null) {
      return Collections.emptyList();
    }

    if (collection instanceof List) {
      return (List) collection;
    }

    return new LinkedList(collection);
  }

  /**
   * Splits linear <code>data</code> into two-dimensional array which has a
   * particular number of <code>columns</code>.
   * 
   * @param data
   * @param columns
   * @return
   */
  @SuppressWarnings("unchecked")
  public static Object split(Collection data, int columns) {

    if (data == null) {
      return EMPTY_ARRAY;
    }

    if (columns <= 0) {
      throw new IllegalArgumentException("A positive value for cols is expected: " + columns);
    }

    int dataSize = data.size();

    int rows = dataSize / columns;
    if (dataSize % columns != 0) {
      rows++;
    }

    Object[] resultArray = new Object[rows];
    Iterator iterator = data.iterator();

    for (int i = 0; i < resultArray.length; i++) {

      int length = columns;
      if (i >= rows - 1 && dataSize % columns != 0) {
        // this is the last row.
        length = dataSize % columns;
      }

      Object[] currentRow = new Object[length];

      for (int j = 0; j < currentRow.length; j++) {
        if (!iterator.hasNext()) {
          break;
        }

        currentRow[j] = iterator.next();
      }

      resultArray[i] = currentRow;
    }

    return resultArray;
  }

  @SuppressWarnings("unchecked")
  public static String toString(Object object) {
    if (object == null) {
      return null;
    }

    return object.toString();
  }

  public static Locale getLocale() {

    UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
    Locale locale = null;

    if (root != null) {
      locale = root.getLocale();
    } else {
      locale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
    }

    return locale;
  }

  public static String getLocalizedString(String label) {
    return getLocalizedString(label, getLocale());
  }

  public static String getLocalizedString(String label, Locale locale) {

    String localizedString;

    try {

      ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_NAME, locale, JagUtils.class.getClassLoader());

      try {
        localizedString = bundle.getString(label);
      } catch (MissingResourceException e) {
        localizedString = "#" + label + "#";
      }

    } catch (MissingResourceException e) {
      localizedString = org.jboss.seam.core.ResourceBundle.instance().getString(label);
    }

    return localizedString;
  }

  public static int hashCode(Object object) {
    if (object == null) {
      return 0;
    }

    return object.hashCode();
  }
}
